package com.dyj.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;
import com.dyj.common.client.AuthClient;
import com.dyj.common.config.AgentConfiguration;
import com.dyj.common.domain.ClientTokenInfo;
import com.dyj.common.domain.query.BaseSubscriptionQuery;
import com.dyj.common.domain.query.BaseTransactionMerchantQuery;
import com.dyj.common.domain.query.ClientTokenQuery;
import com.dyj.common.domain.vo.ClientTokenVo;
import com.dyj.common.domain.vo.TpThirdV2TokenVo;
import com.dyj.common.enums.SubscriptionAccessTokenTypeEnum;
import com.dyj.common.enums.TransactionMerchantTokenTypeEnum;
import com.dyj.common.service.IAgentTokenService;
import com.dyj.common.utils.DyConfigUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 订阅消息接口token拦截器
 */
@Component
public class SubscriptionTokenInterceptor implements Interceptor<Object> {

    private final Log log = LogFactory.getLog(SubscriptionTokenInterceptor.class);

    @Resource
    private ClientTokenInterceptor clientTokenInterceptor;

    @Resource
    private TpV2AuthTokenHeaderInterceptor tpV2AuthTokenHeaderInterceptor;

    @Override
    public boolean beforeExecute(ForestRequest request) {
        SubscriptionAccessTokenTypeEnum accessTokenType = null;
        Object[] arguments = request.getArguments();
        for (Object argument : arguments == null ? new Object[0] : arguments) {
            if (argument instanceof BaseSubscriptionQuery) {
                BaseSubscriptionQuery query = (BaseSubscriptionQuery) argument;
                accessTokenType = query.getAccessTokenTypeEnum();
            }
        }
        if (SubscriptionAccessTokenTypeEnum.TP_V2_AUTH_TOKEN.equals(accessTokenType)){
            //处理服务商token
            return tpV2AuthTokenHeaderInterceptor.beforeExecute(request);
        }else {
            //处理非服务商获取token
           return clientTokenInterceptor.beforeExecute(request);
        }
    }

    @Override
    public void onError(ForestRuntimeException ex, ForestRequest request, ForestResponse response) {
        StringBuilder sb = new StringBuilder("SubscriptionTokenInterceptor onError ");
        sb.append("url:");
        sb.append(request.getUrl());
        sb.append(", ");
        sb.append("params:");
        sb.append(JSONObject.toJSONString(request.getArguments()));
        sb.append(", ");
        sb.append("result:");
        sb.append(response.getContent());
        sb.append(", ");
        sb.append("msg:");
        sb.append(ex.getMessage());
        log.info(sb.toString());
    }

}
